package com.qd.pandaparkflow.compment.park;

import cn.hutool.core.math.Money;
import com.qd.common.panda.domain.entity.rule.Rule3DTO;
import com.qd.pandaparkflow.context.PriceContext;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.NodeComponent;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;

import java.math.BigDecimal;
import java.util.Optional;

/**
 * 有封顶
 * <p>
 * 前两小时5元，以后每小时3元，24小时封顶收费15元
 * [2,500,300,24,1500]
 * {
 * * "startHour": 2,
 * * "startPrice": 5,
 * * "price": 3,
 * * "capTime": 24,
 * * "capPrice": 15
 * * }
 *
 * @author sjk
 */
@ConditionalOnProperty(prefix = "liteflow", name = "enable", havingValue = "true")
@LiteflowComponent(value = "cappedCmp")
public class CappedComponent extends NodeComponent {

    @Override
    public void process() throws Exception {
        //剩余时间
        long timeLeft;
        final PriceContext priceContext = this.getContextBean(PriceContext.class);
        final Rule3DTO rule = (Rule3DTO) priceContext.getRules().get(0);
        int minute = rule.getCapTime() * 60;
        final Long minutes = priceContext.getMinutes();
        Money allPriceBigDecimal = new Money(Optional.ofNullable(priceContext.getFinalOrderPrice()).orElse(new BigDecimal(0L)));
        Money finalOrderPriceBigDecimal = new Money(0L);

        StringBuilder log = new StringBuilder("计算封顶费用,总分钟数[").append(minutes).append("],[")
                .append(rule.getCapTime()).append("小时封顶收费").append(rule.getCapPrice()).append("]");
        if (minutes >= minute) {
            //计算封顶费用
            long a = (minutes / minute);
            timeLeft = minutes % minute;
            finalOrderPriceBigDecimal = finalOrderPriceBigDecimal.add(new Money(a).multiply(rule.getCapPrice()));
            priceContext.setFinalOrderPrice(allPriceBigDecimal.add(finalOrderPriceBigDecimal).getAmount());
            log.append(",满足条件[").append(a).append("],当前金额[").append(finalOrderPriceBigDecimal).append("]");
        } else {
            log.append(",不满足条件");
            timeLeft = minutes;
        }
        log.append(",总金额[").append(priceContext.getFinalOrderPrice().toPlainString()).append("]");
        log.append(",剩余分钟数[").append(timeLeft).append("]");
        priceContext.setHasNextStep(minutes > minute);
        priceContext.setMinutes(timeLeft);
        priceContext.getPrintLog().add(log.toString());
    }
}